package com.imageim.yimirror.common.video;

import android.content.Context;
import android.media.MediaPlayer;
import android.widget.VideoView;

/**
 * Created by Bruce.Zhou on 2018/6/29 16:43.
 * Email: 907160968@qq.com
 */

public class VideoManager {

    private static VideoManager instance;
    private VideoView videoView;

    protected VideoManager() {
    }

    public static VideoManager getInstance() {
        if (instance == null) {
            instance = new VideoManager();
        }
        return instance;
    }

    public void setupVideoView(Context context, final VideoView videoView) {
        this.videoView = videoView;
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
                videoView.start();
            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
//                stopPlaybackVideo();
            }
        });
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                stopPlaybackVideo();
                return true;
            }
        });
//        try {
//            Uri uri = Uri.parse("android.resource://" + BaseApplication.getContext().getPackageName() + "/raw/" + R.raw.banner_video);
//            videoView.setVideoURI(uri);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void stopPlaybackVideo() {
        try {
            videoView.stopPlayback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onResume() {
        if (!videoView.isPlaying()) {
            videoView.resume();
        }
    }

    public void onPause() {
        if (videoView.canPause()) {
            videoView.pause();
        }
    }

}
